package com.feiyu.common.util;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;

import java.util.Map;

/**
 * @author tang ming
 * @since 2021/12/17 12:29
 */
public class WrapperBuilder {
    private static final String IN = "_in";
    private static final String NOT_IN = "_notin";
    private static final String EQUAL = "_eq";
    private static final String NOT_EQUAL = "_noteq";
    private static final String LIKE = "_like";
    private static final String NOT_LIKE = "_notlike";
    private static final String GT = "_gt";
    private static final String LT = "_lt";
    private static final String IS_NULL = "_null";
    private static final String NOT_NULL = "_notnull";

    public  static <T> QueryWrapper<T> getQuery(Map<String,Object> map){
        QueryWrapper<T> qw = new QueryWrapper<>();
        map.forEach((k,v)->{
            if (k.endsWith(IN)){
                qw.in(getColumn(k,IN),JSON.parseArray(String.valueOf(v)));
            } else if(k.endsWith(NOT_IN)){
                qw.notIn(getColumn(k,IN),JSON.parseArray(String.valueOf(v)));
            } else if (k.endsWith(EQUAL)) {
                qw.eq(getColumn(k, EQUAL), v);
            } else if (k.endsWith(NOT_EQUAL)) {
                qw.ne(getColumn(k, NOT_EQUAL), v);
            } else if (k.endsWith(NOT_LIKE)) {
                qw.notLike(getColumn(k, NOT_LIKE), v);
            } else if (k.endsWith(GT)) {
                qw.gt(getColumn(k, GT), v);
            } else if (k.endsWith(LT)) {
                qw.lt(getColumn(k, LT), v);
            } else if (k.endsWith(IS_NULL)) {
                qw.isNull(getColumn(k, IS_NULL));
            } else if (k.endsWith(NOT_NULL)) {
                qw.isNotNull(getColumn(k, NOT_NULL));
            } else {
                qw.eq(k, v);
            }
        });
        return qw;
    }
    public static <T> IPage<T> getPage(Map<String,Object> map) {
        Query query = new Query();
        if(map.containsKey("current"))
            query.setCurrent(Integer.parseInt(String.valueOf(map.remove("current"))));
        if(map.containsKey("size"))
            query.setSize(Integer.parseInt(String.valueOf(map.remove("size"))));
        if (map.containsKey("ascs"))
            query.setAscs(String.valueOf(map.remove("ascs")));
        if (map.containsKey("descs"))
            query.setDescs(String.valueOf(map.remove("descs")));
        return Condition.getPage(query);
    }
    private static String getColumn(String column, String keyword) {
        return column.replace(keyword,"");
    }
}
